//
//  HMPlaceholderTextView.swift
//  sinaweibo
//
//  Created by WGP on 16/4/19.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit

class HMPlaceholderTextView: UITextView {

    var placeholderStr: String?
    {
        didSet
        {
            placeholderLabel.text = placeholderStr
        }
    }
    
    override var font: UIFont?
    {
        didSet
        {
//            HMPrint("override var font")
            placeholderLabel.font = font
        }
    }
    
//    防止外面穿一个默认值
    override var text: String!
    {
        didSet
        {
            placeholderLabel.hidden = self.hasText()
        }
    }

//    MARK: - 构造方法
    override init(frame: CGRect, textContainer: NSTextContainer?) {
            super.init(frame: frame, textContainer: textContainer)
            setupUI()
        
        //        坚挺文字的改变,使用代理不好,在外面别人也有可能使用代理,就会将我们的代理覆盖
        //        使用通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("didChangeText"), name: UITextViewTextDidChangeNotification, object: self)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: - 懒加载
    @objc private func didChangeText()
    {
//        判断有没有文字
        placeholderLabel.hidden = hasText()
    }
    
    private func setupUI()
    {
        self.addSubview(placeholderLabel)
        
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        
//        减少依赖性
       addConstraint( NSLayoutConstraint(item: placeholderLabel, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1, constant: 5))
        
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1, constant: 8))
        
    }
    
//    MARK: - 懒加载
    ///占位label
    private lazy var placeholderLabel: UILabel =
    {
        let label = UILabel()
        
        label.font = self.font
        label.textColor = UIColor.lightGrayColor()
        
        label.text = "分享新鲜事..."
        label.sizeToFit()
        
        return label
    }()
    
    deinit
    {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

}
